package com.minaClient.service;


import org.apache.log4j.Logger;
import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.serialization.ObjectSerializationCodecFactory;
import org.apache.mina.filter.logging.LoggingFilter;
import org.apache.mina.transport.socket.nio.NioSocketConnector;

import java.lang.ref.WeakReference;
import java.net.InetSocketAddress;

/**
 * Description:
 */
public class ConnectionManager {

    private ConnectionConfig mConfig;

    private NioSocketConnector mConnection;
    private IoSession mSession;
    private InetSocketAddress mAddress;
   
    Logger log=Logger.getLogger(ConnectionManager.class.getName());
    public ConnectionManager(ConnectionConfig config){
    	this.mConfig=config;

        init();
    }

    private void init() {
        mAddress = new InetSocketAddress(mConfig.getIp(), mConfig.getPort());
        mConnection = new NioSocketConnector();
        mConnection.getSessionConfig().setReadBufferSize(mConfig.getReadBufferSize());
        mConnection.getFilterChain().addLast("logging", new LoggingFilter());
        mConnection.getFilterChain().addLast("codec", new ProtocolCodecFilter(new ObjectSerializationCodecFactory()));
        mConnection.setHandler(new Iohandler());
        mConnection.setDefaultRemoteAddress(mAddress);
    }

    /**
     * 与服务器连接
     * @return
     */
    @SuppressWarnings("static-access")
	public boolean connnect(){
    	log.debug("tag准备连接");
        try{
            ConnectFuture future = mConnection.connect();
            future.awaitUninterruptibly();
            mSession = future.getSession();

            SessionManager.getInstance().setSeesion(mSession);

        }catch (Exception e){
        	
        	e.printStackTrace();
            log.debug( "连接失败"+e.getMessage());
           
            return false;
        }

        return mSession == null ? false : true;
    }

    /**
     * 断开连接
     */
    public void disContect(){
        mConnection.dispose();
        mConnection=null;
        mSession=null;
        mAddress=null;
        log.debug("断开连接");
    }

   
}
